﻿using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Automation;


namespace YTSK.cSK.HTNew
{
    public class cKP_ZP
    {
        #region DLL

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool GetWindowRect(IntPtr hWnd, ref cDll.RECT lpRect);

        #endregion

        #region 电脑缩放比

        public void GetDpiScale(out float dpiscalex, out float dpiscaley)
        {
            const int DESKTOPVERTRES = 117;
            const int DESKTOPHORZRES = 118;

            const int SM_CXSCREEN = 0;
            const int SM_CYSCREEN = 1;
            int x = cDll.GetSystemMetrics(SM_CXSCREEN);
            int y = cDll.GetSystemMetrics(SM_CYSCREEN);
            IntPtr hdc = cDll.GetDC(IntPtr.Zero);
            int w = cDll.GetDeviceCaps(hdc, DESKTOPHORZRES);
            int h = cDll.GetDeviceCaps(hdc, DESKTOPVERTRES);
            cDll.ReleaseDC(IntPtr.Zero, hdc);
            dpiscalex = (float) w / x;
            dpiscaley = (float) h / y;
        }

        #endregion

        public static string proc(string filePath, out string fpdm, out string fphm)
        {
            var err = "";
            fpdm = "";
            fphm = "";
            IntPtr hWnd = cDll.FindWindow(null, "布局"); //获取新开票句柄
            if (hWnd.ToInt32() == 0)
            {
                err = $"没有找到[增值税发票税控开票软件（金税盘版）]窗口或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }
            
            // var l_win = cDllExt.GetAllChild(IntPtr.Zero);
            // var l_win_tmp = l_win.Where(s => s.text == "布局").ToList();
            // var tmp_win = l_win_tmp.FirstOrDefault(s =>
            //     s.position.Width - s.position.Left > 950 && s.position.Height - s.position.Top > 700);
            // if (tmp_win == null)
            // {
            //     err = $"没有找到[增值税发票税控开票软件（金税盘版）]窗口或者系统运行速度太慢，请与系统管理员联系";
            //     return err;
            // }
            // var hWnd = tmp_win.hwnd;
            
            
            cDll.SetForegroundWindow(hWnd); //设置为活动窗口
            cDll.ShowWindow(hWnd, 1);
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());

            #region 对指定句柄窗口截图

            cDll.RECT rectSrc = new cDll.RECT();
            GetWindowRect(hWnd, ref rectSrc);
            // cDll.GetClientRect(hWnd, out rectSrc);
            int widthSrc = rectSrc.Right - rectSrc.Left; //窗口的宽度
            int heightSrc = rectSrc.Bottom - rectSrc.Top; //窗口的高度
            int xSrc = rectSrc.Left;
            int ySrc = rectSrc.Top;

            #endregion

            #region 专用发票判断

            double threshold = 0.0;
            int icountzp = 0;
            do
            {
                cDll.SwitchToThisWindow(hWnd, true);
                var imgSrcZP = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc);
                var impzpht = Properties.Resources.zp_ht;
                System.Drawing.Point zp = Common.HandleImg.FindPicFromImage(imgSrcZP, impzpht);
                var wtzp = impzpht.Width;
                var htzP = impzpht.Height;
                var imgZPCut =
                    Common.HandleImg.GetScreenImg(rectSrc.Left + zp.X, rectSrc.Top + zp.Y, wtzp, htzP); //对样本位置截图
                // imgZPCut.Save("C:\\税控接口\\image\\imgCut.png");
                threshold = Common.HandleImg.MatchPicBySift(impzpht, imgZPCut);
                icountzp++;
                Thread.Sleep(250);
            } while (threshold < 0.9 && icountzp < 30);

            if (threshold < 0.9)
            {
                err = "这不是专用发票，请正确使用发票填开！";
                return err;
            }

            #endregion

            var imgSrc = Common.HandleImg.GetScreenImg(xSrc, ySrc, widthSrc, heightSrc);
            Thread.Sleep(300);
            var imgImp = Properties.Resources.import_ht;
            System.Drawing.Point picFromSrc = Common.HandleImg.FindPicFromImage(imgSrc, imgImp); //导入
            var wtImp = imgImp.Width; //获取图片尺寸，计算中心点
            var htImp = imgImp.Height;
            var xOfsImp = wtImp / 2;
            var yOfsImp = htImp / 2;
            var clickSubx = rectSrc.Left + picFromSrc.X + xOfsImp; //加偏移量xOfsImp，尽量靠近中心点  35（固定偏移量）
            var clickSuby = rectSrc.Top + picFromSrc.Y + yOfsImp; //加偏移量yOfsImp，尽量靠近中心点   20（固定偏移量）
            cDllExt.mouseClick(clickSubx, clickSuby);

            #region 选择导入文件

            var ifindount = 0;
            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt());
            var openwin = new Model.WinProperty();
            var sname = new StringBuilder();
            sname.Append("打开");
            openwin.hwnd = cDll.FindWindow(null, sname);
            while (openwin.hwnd.ToInt32() == 0 && ifindount < 10)
            {
                ifindount++;
                openwin.hwnd = cDll.FindWindow(null, sname);
                Thread.Sleep(300);
            }

            if (openwin.hwnd.ToInt32() == 0)
            {
                err = $"没有找到窗口[{sname}]或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            cDllExt.GetWinProperty(openwin);
            var openmainOle = AutomationElement.FromHandle(openwin.hwnd);
            if (openmainOle == null)
            {
                err += "没有找到输入窗体";
                return err;
            }

            var condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
            var condition1 = new PropertyCondition(AutomationElement.NameProperty, "文件名(N):");
            var andcondition = new AndCondition(condition0, condition1);
            var eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
            ifindount = 0;
            while (eliemt == null && ifindount < 5)
            {
                eliemt = openmainOle.FindFirst(TreeScope.Descendants, andcondition);
                ifindount++;
                if (eliemt == null)
                {
                    System.Threading.Thread.Sleep(500);
                }
            }

            var vt = (ValuePattern) eliemt.GetCurrentPattern(ValuePattern.Pattern);
            vt.SetValue(filePath);
            condition0 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button);
            condition1 = new PropertyCondition(AutomationElement.NameProperty, "打开(O)");
            andcondition = new AndCondition(condition0, condition1);
            eliemt = openmainOle.FindFirst(TreeScope.Children, andcondition);
            if (eliemt == null)
            {
                eliemt = openmainOle.FindFirst(TreeScope.Children, condition1);
            }

            if (eliemt == null)
            {
                var itop = openwin.position.Top - 50 + 25;
                var ileft = openwin.position.Left - 213 + 40;
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
            }
            else
            {
                var rect = eliemt.Current.BoundingRectangle;
                var itop = (int) (rect.Top + rect.Height / 2);
                var ileft = (int) (rect.Left + rect.Width / 2);
                cDll.SetCursorPos(ileft, itop);
                cDllExt.mouseDoubleClick(ileft, itop);
            }

            #endregion

            Thread.Sleep(cSKSet.loadsave(SkConfig.延时设置).ObjToInt() * 3);

            #region 再次对指定句柄窗口截图

            IntPtr hWnd2 = cDll.FindWindow(null, "导入单据查询信息"); //获取新开票句柄
            if (hWnd2.ToInt32() == 0)
            {
                err = $"没有找到[导入单据查询信息]窗口或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }


            cDll.SetForegroundWindow(hWnd2); //设置为活动窗口
            cDll.RECT rectSrc2 = new cDll.RECT();
            GetWindowRect(hWnd2, ref rectSrc2);
            int widthSrc2 = rectSrc2.Right - rectSrc2.Left; //窗口的宽度
            int heightSrc2 = rectSrc2.Bottom - rectSrc2.Top; //窗口的高度
            int xSrc2 = rectSrc2.Left;
            int ySrc2 = rectSrc2.Top;
            var imgSrc2 = Common.HandleImg.GetScreenImg(xSrc2, ySrc2, widthSrc2, heightSrc2);

            #endregion

            ReImport:
            double threshold2 = 0.0;
            // int ihwnd2_1 = 0;
            IntPtr hWnd2_1 = IntPtr.Zero;
            int icountSel = 0;
            do
            {
                // cDll.SwitchToThisWindow(hWnd2, true);
                var imgsel = Properties.Resources.select_ht;
                System.Drawing.Point picFromSrc3 = Common.HandleImg.FindPicFromImage(imgSrc2, imgsel); //选择发票
                var wtsel = imgsel.Width; //获取图片尺寸，计算中心点
                var htsel = imgsel.Height;
                var xOfssel = wtsel * 1 / 2;
                var yOfssel = htsel * 1 / 2;
                var clickSubx3 = rectSrc2.Left + picFromSrc3.X + xOfssel; //加偏移量xOfsImp，尽量靠近中心点
                var clickSuby3 = rectSrc2.Top + picFromSrc3.Y + yOfssel; //加偏移量yOfsImp，尽量靠近中心点
                cDllExt.mouseClick(clickSubx3, clickSuby3);

                var imgImp2 = Properties.Resources.import_ht_2;
                System.Drawing.Point picFromSrc2 = Common.HandleImg.FindPicFromImage(imgSrc2, imgImp2); //第二次导入
                var wtImp2 = imgImp2.Width; //获取图片尺寸，计算中心点
                var htImp2 = imgImp2.Height;
                var xOfsImp2 = wtImp2 * 2 / 3;
                var yOfsImp2 = htImp2 * 2 / 3;
                var clickSubx2 = rectSrc2.Left + picFromSrc2.X + xOfsImp2; //加偏移量xOfsImp，尽量靠近中心点
                var clickSuby2 = rectSrc2.Top + picFromSrc2.Y + yOfsImp2; //加偏移量yOfsImp，尽量靠近中心点
                cDllExt.mouseClick(clickSubx2, clickSuby2);

                // hWnd2_1 = cDll.FindWindow(null, "导入单据查询信息"); //获取新开票句柄
                var imgSrc2_1 = Common.HandleImg.GetScreenImg(xSrc2, ySrc2, widthSrc2, heightSrc2);
                threshold2 = Common.HandleImg.MatchPicBySift(imgSrc2, imgSrc2_1);
                icountSel++;
                Thread.Sleep(500);
            } while (threshold2 == 1 && icountSel < 10);
            
            Thread.Sleep(250);
            hWnd2_1 = cDll.FindWindow(null, "导入单据查询信息"); //获取新开票句柄
            if (hWnd2_1.ToInt32() > 0)
            {
                cDll.SwitchToThisWindow(hWnd2_1, true);
                GetWindowRect(hWnd2_1, ref rectSrc2);
                widthSrc2 = rectSrc2.Right - rectSrc2.Left; //窗口的宽度
                heightSrc2 = rectSrc2.Bottom - rectSrc2.Top; //窗口的高度
                xSrc2 = rectSrc2.Left;
                ySrc2 = rectSrc2.Top;
                imgSrc2 = Common.HandleImg.GetScreenImg(xSrc2, ySrc2, widthSrc2, heightSrc2);
                goto ReImport;
            }


            #region 再次对指定句柄窗口截图

            IntPtr hWnd3 = cDll.FindWindow(null, "布局"); //获取新开票句柄
            if (hWnd3.ToInt32() == 0)
            {
                err = $"没有找到[增值税发票税控开票软件（金税盘版）]窗口或者系统运行速度太慢，请与系统管理员联系";
                return err;
            }

            cDll.SetForegroundWindow(hWnd3); //设置为活动窗口
            cDll.RECT rectSrc3 = new cDll.RECT();
            GetWindowRect(hWnd3, ref rectSrc3);
            int widthSrc3 = rectSrc3.Right - rectSrc3.Left; //窗口的宽度
            int heightSrc3 = rectSrc3.Bottom - rectSrc3.Top; //窗口的高度
            int xSrc3 = rectSrc3.Left;
            int ySrc3 = rectSrc3.Top;
            var imgSrc3 = Common.HandleImg.GetScreenImg(xSrc3, ySrc3, widthSrc3, heightSrc3);
            // imgSrc3.Save("C:\\税控接口\\image\\imgSrc3_HTNew.png");

            #endregion

            #region 发票代码-发票号码

            int icount = 0;
            while ((fpdm.ObjToString().Length == 0 || fphm.ObjToString().Length == 0) && icount < 30)
            {
                //发票代码
                var imgfadm = Properties.Resources.fpdm_ht;
                var imgfpdm1 = Properties.Resources.fpdm_ht_noNo; //用文字部分进行样本定位，保证准确度
                System.Drawing.Point pointfpdm = Common.HandleImg.FindPicFromImage(imgSrc3, imgfpdm1);
                var wtfpdm = imgfadm.Width;
                var htfpdm = imgfadm.Height;
                var fpdmx = rectSrc3.Left + pointfpdm.X;
                var fpdmy = rectSrc3.Top + pointfpdm.Y;
                var fpdmbmp =
                    Common.HandleImg.GetScreenImg(fpdmx + 77, fpdmy, wtfpdm - 5, htfpdm - 3);
                fpdmbmp = Common.HandleImg.PicProcess(fpdmbmp); //截图优化处理
                var ocrfpdm = Common.HandleImg.Reconize(OcrType.发票代码, fpdmbmp);
                var matchfpdm = System.Text.RegularExpressions.Regex.Match(ocrfpdm, "\\d{10,12}");
                fpdm = matchfpdm.Value;
                //发票号码
                var imgfphm = Properties.Resources.fphm_ht;
                var imgfphm1 = Properties.Resources.fphm_ht_noNo; //用文字部分进行样本定位，保证准确度
                System.Drawing.Point pointfphm = Common.HandleImg.FindPicFromImage(imgSrc3, imgfphm1);
                var wtfphm = imgfphm.Width;
                var htfphm = imgfphm.Height;
                var fphmx = rectSrc3.Left + pointfphm.X;
                var fphmy = rectSrc3.Top + pointfphm.Y;
                var fphmbmp =
                    Common.HandleImg.GetScreenImg(fphmx + 75, fphmy, wtfphm, htfphm);
                fphmbmp = Common.HandleImg.PicProcess(fphmbmp); //截图优化处理
                // fphmbmp.Save("C:\\税控接口\\image\\fphmbmp_HTNew.png");
                var ocrfphm = Common.HandleImg.Reconize(OcrType.发票号码, fphmbmp);
                var matchfphm = System.Text.RegularExpressions.Regex.Match(ocrfphm, "\\d{8}");
                fphm = matchfphm.Value;
                Thread.Sleep(250);
                icount++;
            }

            #endregion

            return "";
        }
    }
}